import Cookies from "js-cookie";
import axios from "axios";
import router from "@/router";

const state = {
  loginStatus: 0,
  username: undefined,
  userId: undefined,
};

const mutations = {
  LOGIN: (state, { isLoginSuccess, user }) => {
    if (isLoginSuccess) {
      state.loginStatus = 1;
      state.username = user.username;
      state.userId = user.id;
      Cookies.set("loginStatus", 1);
      Cookies.set("username", user.username);
      Cookies.set("userId", user.id);
    } else {
      state.loginStatus = 0;
      Cookies.set("loginStatus", 0);
      Cookies.set("username", "");
      Cookies.set("userId", "");
    }
  },
};

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    axios.post("api/login", { username, password }).then((res) => {
      commit("LOGIN", { isLoginSuccess: 1, user: res.data.data });
      router.push({ path: "/" });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
